﻿/*
 * PsTFS is a set of PowerShell commands to manage and use Team Foundation Server. PowerShell 
 * effectiveness is combined with the power of TFS API to maximizes TFS capabilities.
 * 
 * Creator : Choulant Noham
 * Mail : choulant@gmail.com
 * Blog : http://choulant.blogspot.com
 * 
 */

using System;
using System.Management.Automation;
using Microsoft.TeamFoundation.Build.Workflow.Activities;
using Microsoft.TeamFoundation.Client;
using PsTFS.Methodes;
using PsTFS.Objects;
using Microsoft.TeamFoundation.Build.Workflow;
using Microsoft.TeamFoundation.Build.Workflow.Activities;

namespace PsTFS.Commandes.Start
{
    /// <summary>
    /// Récupération de la liste des build pour un projet d'un serveur TFS
    /// </summary>
	[Cmdlet(VerbsLifecycle.Start, "Build")]
    public class StartBuild : PsCmdlet
    {
        /// <summary>
        /// Lancement du processus de lancement d'une BUILD d'un projet
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
	            var buildDef = Context.Instance.BuildServer.GetBuildDefinition(ProjectName, BuildName);
	            var buildRequest = buildDef.CreateBuildRequest();
	            if (!string.IsNullOrWhiteSpace(MSBuildParameters))
	            {
					var options = WorkflowHelpers.DeserializeProcessParameters(buildRequest.ProcessParameters);
					options["MSBuildArguments"] = MSBuildParameters;
					buildRequest.ProcessParameters = WorkflowHelpers.SerializeProcessParameters(options);
	            }
				WriteObject(Context.Instance.BuildServer.QueueBuild(buildRequest));

            }
			catch (Exception ex)
            {
				var err = ErrorRecord(ex, ErrorCategory.WriteError);
				WriteError(err);
				Log.AddLog(ex.StackTrace);
			}
            finally
            {
                base.ProcessRecord();
            }
        }

		/// <summary>
        /// Permet d'informer la fin de la commande
        /// </summary>
        protected override void EndProcessing()
        {
            Log.AddLog(null, "Start-Build is endding");
            base.EndProcessing();
        }

		/// <summary>
        /// Object contenant Team Foundation Server
        /// </summary>
        [Parameter(Position = 0)]
        public TfsTeamProjectCollection TFS
        {
            set { Context.Instance.TFS = value; }
        }

		/// <summary>
        /// Nom du label
        /// </summary>
        [Parameter(Position = 1)]
        public string ProjectName { get; set; }

        /// <summary>
        /// Nom de la build
        /// </summary>
        [Parameter(Position = 2)]
        public string BuildName { get; set; }

		/// <summary>
		/// MSBuild parameters to pass to the build
		/// </summary>
		[Parameter(Position = 3)]
// ReSharper disable once InconsistentNaming
		public string MSBuildParameters { get; set; }

    }
}